//
//  GMExerciseCardVC.m
//  Teecloud
//
//  Created by 小熊 on 2018/11/19.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "GMExerciseCardVC.h"
#import "GMResultCell.h"
#import "GMSubjectsModel.h"
#import "GMAnswerItem.h"
#import "GMExamResultVC.h"
#import "GMResultVC.h"
@interface GMExerciseCardVC ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UILabel *titleName;
@property (nonatomic, copy) NSArray *dataArr;

@end

@implementation GMExerciseCardVC


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"答题卡";
    [self.collectionView registerNib:[UINib nibWithNibName:@"GMResultCell" bundle:nil] forCellWithReuseIdentifier:@"GMResultCell"];
    self.titleName.text = self.baseModel.Title;
    self.dataArr = self.baseModel.Subjects;
    [self.collectionView reloadData];
}
#pragma mark - CollectionView代理
//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    GMResultCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GMResultCell" forIndexPath:indexPath];
    GMSubjectsModel *subModel = self.dataArr[indexPath.row];
    cell.subModel = subModel;
    return cell;
}
//设置每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((DEVICE_WIDTH-60)/5, 50);
}

//设置每个item的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 10, 10,10);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}


//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    /**发送通知，定位当前题目*/
    GMSubjectsModel *subModel = self.dataArr[indexPath.row];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"GMExercisesVC" object:subModel];
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)sumbitBtnClick:(id)sender {
    for (GMSubjectsModel *subModel in self.dataArr) {
        if (kIsEmptyString(subModel.Answer)) {
            //如果有题目未答，提醒
            UIAlertController *alert  = [UIAlertController zj_alertControllerWithTitle:@"" message:@"还有题目未作答，继续提交吗？" optionStyle:OptionStyleStyleOK_Cancel OkTitle:@"确定" cancelTitle:@"取消" okBlock:^{
                [self handerOK];
            } cancelBlock:^{
                
            }];
            [self presentViewController:alert animated:YES completion:nil];
            /**找到如果有题目未答，直接退出循环*/
            return;
        }
        
    }
    //如果全答完
     [self handerOK];
}
-(void)handerOK{
    NSMutableArray *sumbitArr = [[NSMutableArray alloc] init];
    for (NSInteger i =0; i<self.dataArr.count; i++) {
        GMSubjectsModel *subModel = self.dataArr[i];
        NSDictionary *sumbitDict = @{@"Id":subModel.Id,
                                     @"SortNo":subModel.SortNo,
                                     @"Answer":subModel.Answer?subModel.Answer:@"",
                                     @"StartTime":subModel.StartTime?subModel.StartTime:[NSString getCurrentTimes],
                                     @"UseTime":subModel.UseTime?subModel.UseTime:@(0)
                                     };
        [sumbitArr addObject:sumbitDict];
    }
    NSString *jsonString = sumbitArr.mj_JSONString;
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"examId":self.baseModel.Id,
                          @"subjectData":jsonString
                          };
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=PostExamData&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                GMResultVC *result = [[GMResultVC alloc] init];
                result.examId = self.baseModel.Id;
                [self.navigationController pushViewController:result animated:YES];
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:self.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:self.view];
        }
    }];
}
@end
